﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Diagnostics;

namespace SimpleBasicAuthentication
{
    /// <summary>
    /// Our own implementation of Basic Authentication
    /// 
    /// based on http://blogs.msdn.com/b/astoriateam/archive/2010/07/21/odata-and-authentication-part-6-custom-basic-authentication.aspx
    /// </summary>
    public class BasicAuthenticationModule : IHttpModule
    {
        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            //EventLog.WriteEntry("Application", "*** Entry for BasicAuthenticationModule HttpModule: Init");

            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        /// <summary>
        /// Handles the AuthenticateRequest event of the context control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            //EventLog.WriteEntry("Application", "*** Entry for BasicAuthenticationModule HttpModule: context_AuthenticateRequest");
            
            HttpApplication application = (HttpApplication)sender;
            if (!BasicAuthenticationProvider.Authenticate(application.Context, false))
            {
                application.Context.Response.Status = "401 Unauthorized";
                application.Context.Response.StatusCode = 401;
                application.Context.Response.AddHeader("WWW-Authenticate", "Basic");
                application.CompleteRequest();
            }
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
        /// Leave empty!
        /// </summary>
        public void Dispose() { }
    }
}